<?php
require 'model-db-connection/config.php';
$config = require 'model-db-connection/qrc_conf.properties.php';
$searchCondition = $_GET['searchCondition'];
$memId = $_GET['memId'];
$memName = $_GET['memName'];
$memRole = $_GET['memRole'];
$memberSkill = $_GET['memberSkill'];
$teamCode = $_GET['teamCode'];
$teamName = $_GET['teamName'];
?>
<div class="widget">
    <div class="widget-head">
        <h4 class="heading">Member (ลูกทีม)</h4>
        <a href="#modal-member" data-toggle="modal" class="btn btn-xs btn-inverse pull-right" id="new_member_btn" style="margin-top: 6px;"><i class="fa fa-plus fa-fw"></i> New Member</a>
        <div class="clearfix"></div>
    </div>
    <div class="widget-body innerAll inner-2x">
        <!-- Table -->
        <table class="footable table table-striped table-primary dynamicTable tableTools" id="dataTables-member">

            <!-- Table heading -->
            <thead>
                <tr>
                    <th data-class="expand" class="center">Member ID</th>
                    <th class = "center">Member Name</th>
                    <th class = "center">Role</th>
                    <th data-hide="phone,tablet">Skill(s)</th>
                    <th data-hide="phone,tablet">Tel.</th>
                    <th data-hide="phone,tablet">Email</th>
                    <th data-hide="phone,tablet">Remark</th>
                    <th class = "center">Team Code</th>
                    <th class = "center">Team Name</th>
                    <th></th>
                </tr>
            </thead>
            <!-- // Table heading END -->
            <!-- Table body -->
            <tbody>
                <?php
                if ($searchCondition == "search_all" || $searchCondition == "") {
                    $sqlSelectMemberAll = "SELECT qm.memID AS mem_id,"
                            . "qm.memName AS mem_name,"
                            . "qmr.role_name AS mem_role,"
                            . "qm.memTel AS mem_tel,"
                            . "qm.memEmail AS mem_email,"
                            . "qm.memSkill AS mem_skill,"
                            . "qm.memTCode AS mem_t_code,"
                            . "qm.memTName AS mem_t_name,"
                            . "qm.memRemark AS mem_remark"
                            . " FROM QRC_MEMBERS qm"
                            . " LEFT JOIN QRC_TEAM_BUILDER qtb ON qm.memTCode =qtb.tCode"
                            . " LEFT JOIN QRC_MEMBER_ROLE qmr ON qm.memRole = qmr.role_id"
                            . " ORDER BY qm.memID DESC;";
                } else {
                    $checkMemId = !empty($memId) ? " AND qm.memID LIKE '%$memId%'" : "";
                    $checkMemName = !empty($memName) ? " AND qm.memName LIKE '%$memName%'" : "";
                    $checkMemRole = !empty($memRole) ? " AND qm.memRole LIKE '$memRole'" : "";
                    $checkTCode = !empty($teamCode) ? " AND qm.memTCode LIKE '%$teamCode%'" : "";
                    $checkTName = !empty($teamName) ? " AND qm.memTName LIKE '%$teamName%'" : "";
                    if ($memberSkill == "null") {
                        $checkMemSkill = "";
                    } else {
                        $checkMemSkill = !empty($memberSkill) ? " AND qsa.SKILL_ID IN ($memberSkill)" : "";
                    }

                    $sqlSelectMemberAll = "SELECT DISTINCT qm.memID AS mem_id,"
                            . "qm.memName AS mem_name,"
                            . "qmr.role_name AS mem_role,"
                            . "qm.memTel AS mem_tel,"
                            . "qm.memEmail AS mem_email,"
                            . "qm.memSkill AS mem_skill,"
                            . "qm.memTCode AS mem_t_code,"
                            . "qm.memTName AS mem_t_name,"
                            . "qm.memRemark AS mem_remark"
                            . " FROM QRC_MEMBERS qm"
                            . " LEFT JOIN QRC_TEAM_BUILDER qtb ON qm.memTCode =qtb.tCode"
                            . " LEFT JOIN QRC_MEMBER_ROLE qmr ON qm.memRole = qmr.role_id"
                            . " LEFT JOIN QRC_SKILL_ATTR qsa ON qm.memID = qsa.M_T_REF_ID"
                            . " WHERE 1=1"
                            . $checkMemId
                            . $checkMemName
                            . $checkMemRole
                            . $checkTCode
                            . $checkTName
                            . $checkMemSkill
                            . " ORDER BY qm.memID DESC;";
                }
                $sqlGetAllData = mysql_query($sqlSelectMemberAll);
//                echo $sqlSelectMemberAll;
                if (mysql_num_rows($sqlGetAllData) >= 1) {
                    while ($row = mysql_fetch_assoc($sqlGetAllData)) {
                        echo '<tr class = "gradeX">';
                        echo '<td>' . $row['mem_id'] . '</td>';
                        echo '<td>' . $row['mem_name'] . '</td>';
                        echo '<td>' . $row['mem_role'] . '</td>';
                        $skills = explode(",", $row['mem_skill']);
                        $j = 0;
                        for ($i = 0; $i <= count($skills); $i++) {
                            $sqlGetNameOfSkill = "SELECT service_name FROM QRC_TYPE_OF_SERVICE WHERE service_id like '$skills[$i]'";
                            $sqlGetSkillFromID = mysql_query($sqlGetNameOfSkill);
                            while ($rows = mysql_fetch_assoc($sqlGetSkillFromID)) {
                                if ($j == 0) {
                                    $strResult.= $rows['service_name'];
                                    $j = 1;
                                } else {
                                    $strResult.= " , " . $rows['service_name'];
                                }
                            }
                        }
                        echo '<td>' . $strResult . '</td>';
                        echo '<td>' . $row['mem_tel'] . '</td>';
                        echo '<td>' . $row['mem_email'] . '</td>';
                        echo '<td>' . $row['mem_remark'] . '</td>';
                        if ($row['mem_t_code'] == "") {
                            echo '<td class = "center">-</td>';
                            echo '<td class = "center">-</td>';
                        } else {
                            echo '<td>' . $row['mem_t_code'] . '</td>';
                            echo '<td>' . $row['mem_t_name'] . '</td>';
                        }
                        echo '<td class = "center">';
                        echo '<a href = "#modal-member" data-toggle = "modal" class = "btn btn-primary" onclick=editMember("' . $row['mem_id'] . '")><i class = "icon-document-line"></i> Edit</a>';
                        echo '<button class = "btn btn-danger" style="margin-left: 5px" onclick=deleteMember("' . $row['mem_id'] . '")><i class = "fa fa-trash-o"></i> Delete</button>';

                        echo '</td>';
                        echo '</tr>';
                        $strResult = "";
                    }
                }
                ?>
            </tbody>
            <!-- // Table body END -->

        </table>
        <!-- // Table END -->

    </div>
</div>
<script src="assets/components/common/tables/responsive/assets/lib/js/footable.min.js?v=v1.0.2&sv=v0.0.1"></script>
<script src="assets/components/common/tables/responsive/assets/custom/js/tables-responsive-footable.init.js?v=v1.0.2&sv=v0.0.1"></script>
<script src="assets/components/modules/admin/notifications/gritter/assets/lib/js/jquery.gritter.min.js?v=v1.0.2&sv=v0.0.1"></script>
<script src="assets/components/modules/admin/modals/assets/js/bootbox.min.js?v=v1.0.2&sv=v0.0.1"></script>
<script src="assets/components/common/forms/elements/multiselect/assets/lib/js/jquery.multi-select.js?v=v1.0.2&sv=v0.0.1"></script>
<script src="assets/components/common/forms/elements/multiselect/assets/custom/js/multiselect.init.js?v=v1.0.2&sv=v0.0.1"></script>
<script src="assets/components/common/forms/elements/select2/assets/lib/js/select2.js?v=v1.0.2&sv=v0.0.1"></script>
<script src="assets/components/common/forms/elements/select2/assets/custom/js/select2.init.js?v=v1.0.2&sv=v0.0.1"></script>
<div class="modal fade" id="modal-member">

    <div class="modal-dialog">
        <div class="modal-content" style="width: 900px">

            <!-- Modal heading -->
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                <h2 class="modal-title">Member Create/Edit</h2>
            </div>
            <!-- // Modal heading END -->

            <!-- Modal body -->
            <div class="modal-body">
                <div class="innerAll">
                    <div class="innerLR">
                        <table width="100%">
                            <tr>
                                <td align="right" style="width:250px">Member ID (หมายเลขประจำตัว):</td>
                                <td align="left" style="width:250px">
                                    <?php
                                    $sqlSelectMaxValue = "SELECT count(*) as total FROM QRC_MEMBERS";
                                    $resultSet = mysql_query($sqlSelectMaxValue);
                                    $row = mysql_fetch_assoc($resultSet);
                                    if ($row['total'] == 0) {
                                        echo '<input type="text" class="form-control" id="member_id_form" disabled="true" value="M0001"/>';
                                    } else {
                                        $sqlSelectCodeValue = "SELECT max(memID) as code FROM QRC_MEMBERS";
                                        $resultSets = mysql_query($sqlSelectCodeValue);
                                        $row = mysql_fetch_assoc($resultSets);
                                        $prefix = "M";
                                        $pieces = explode("M", $row[code]);
                                        if (count(intval($pieces[1])) == 1) {
                                            $strResult = $prefix . "000" . (intval($pieces[1] + 1));
                                        } else if (count(intval($pieces[1])) == 2) {
                                            $strResult = $prefix . "00" . (intval($pieces[1] + 1));
                                        } else if (count(intval($pieces[1])) == 3) {
                                            $strResult = $prefix . "0" . (intval($pieces[1] + 1));
                                        } else {
                                            $strResult = $prefix . (intval($pieces[1] + 1));
                                        }
                                        echo '<input type="text" class="form-control" id="member_id_form" disabled="true" value="' . $strResult . '"/>';
//                                        echo '<input type="hidden" name="member_id" id="member_id" value="' . $strResult . '"/>';
                                    }
                                    ?>
                                </td>
                                <td align="right" style="width:250px">Member Name (ชื่อ-สกุล):</td>
                                <td align="left" style="width:250px"><input type="text" class="form-control" id="member_name_form" name="member_name"/></td>
                            </tr>
                            <tr>
                                <td align="right" style="width:250px">Role (ตำแหน่ง):</td>
                                <td align="left" style="width:250px">
                                    <select class="form-control" id="member_role_form" name="member_role_form">
                                        <option value=""></option>
                                        <?php
                                        $sqlSelectProjectType = "SELECT * FROM QRC_MEMBER_ROLE;";
                                        $resultSet = mysql_query($sqlSelectProjectType);
                                        while ($row = mysql_fetch_array($resultSet)) {
                                            echo '<option value="' . $row['role_id'] . '">' . $row['role_name'] . '</option>';
                                        }
                                        ?>
                                    </select>
                                </td>
                                <td align="right" style="width:250px">Skill (ความสามารถ):</td>
                                <td align="left" style="width:250px">
                                    <select multiple="multiple" style="width: 100%;" id="member_skill_form" name="skill">

                                        <?php
                                        $sqlSelectProjectType = "SELECT * FROM QRC_TYPE_OF_SERVICE;";
                                        $resultSet = mysql_query($sqlSelectProjectType);
                                        while ($row = mysql_fetch_array($resultSet)) {
                                            echo '<option value="' . $row['service_id'] . '">' . $row['service_name'] . '</option>';
                                        }
                                        ?>                        
                                    </select>
                                    <span id="waringmsg" style="color: red; font-size: 11px;"></span>
                                </td>
                            </tr>
                            <tr>
                                <td align="right" style="width:250px">Team Code (หมายเลขทีมช่าง):</td>
                                <td align="left" style="width:250px">
                                    <select class="form-control" id="team_code_in_member_form2" name="team_code_in_member_form">
                                        <option value=""></option>
                                        <?php
                                        $sqlSelectProjectType = "SELECT * FROM QRC_TEAM_BUILDER;";
                                        $resultSet = mysql_query($sqlSelectProjectType);
                                        while ($row = mysql_fetch_array($resultSet)) {
                                            echo '<option value="' . $row['tCode'] . '">' . $row['tCode'] . '</option>';
                                        }
                                        ?>
                                    </select>
                                </td>
                                <td align="right" style="width:250px">Team Name (ชื่อทีม):</td>
                                <td align="left" style="width:250px"><input type="text" class="form-control" id="team_name_in_member_form2" disabled="true"></td>
                            </tr>

                            <tr>
                                <td align="right" style="width:250px">Tel:</td>
                                <td align="left" style="width:250px"><input type="text" class="form-control" id="tel_in_member_form"></td>
                                <td align="right" style="width:250px">Email:</td>
                                <td align="left" style="width:250px"><input type="text" class="form-control" id="email_in_member_form"></td>
                            </tr>
                            <tr>
                                <td align="right" style="width:250px">Remark:</td>
                                <td align="left" colspan="3"><input type="text" class="form-control" id="remark_inform"></td>

                            </tr>
                            <tr>
                                <td align="right" style="width:250px" colspan="2"><button class = "btn btn-primary" style="margin-left: 5px" id="member_builder_create_btn">Create Member (สร้าง)</button></td>
                                <td align="left" style="width:250px" colspan="2"><button class="btn btn-primary" style="margin-left: 5px" id="member_builder_cancel_btn">Cancel (ยกเลิก)</button></td>

                            </tr>
                        </table>
                    </div>
                </div>
            </div>
            <!-- // Modal body END -->

        </div>
    </div>
    <input type="hidden" id="hideMemSkill"/>
</div>
<script type="text/javascript">
    var createOrEditState = "Save";
    $(document).ready(function() {
        $("#dataTables-member").dataTable();
        $("#team_code_in_member_form2").change(function() {
            var tCode = $("#team_code_in_member_form2").val();
            var jqxhr = $.post("model/GetTName.php?tCode=" + tCode);
            jqxhr.success(function(data) {
                $("#team_name_in_member_form2").val(data);
            });
            jqxhr.error(function(data) {
                window.location.replace("error.php?error_msg=" + data);
            });
        });
        $("#new_member_btn").click(function() {
            createOrEditState = "Save";
        });
        $("#member_builder_cancel_btn").click(function() {
            blockPage();
            createOrEditState = "Save";
            $("#waringmsg").empty();
            $("#modal-member").modal('hide');
            setTimeout(function()
            {
                $("#load_member").load("MemberMainPage.php?searchCondition=search_all", function() {
                    $.unblockUI();
                });

            }
            , 500);
        });
        $("#member_builder_create_btn").click(function() {
            blockPage();
            var memId = $("#member_id_form").val();
            var memName = $("#member_name_form").val();
            var memRole = $("#member_role_form").val();
            var memberSkill = $("#member_skill_form").val();
            var teamCode = $("#team_code_in_member_form2").val();
            var teamName = $("#team_name_in_member_form2").val();
            var tel = $("#tel_in_member_form").val();
            var email = $("#email_in_member_form").val();
            var remark_inform = $("#remark_inform").val();

            if (createOrEditState == "Edit") {
                if (remark_inform == "") {
                    alert("กรุณาใส่ Remark");
                    $.unblockUI();
                } else {
                    if (memberSkill == null || memberSkill == "") {
                        memberSkill = $("#hideMemSkill").val();
                        var jqxhr = $.post("model/EditMember.php?memId=" + memId + "&memName=" + memName + "&memRole=" + memRole + "&memberSkill=" + memberSkill + "&teamCode=" + teamCode + "&teamName=" + teamName + "&tel=" + tel + "&email=" + email + "&remark=" + remark_inform);
                        jqxhr.success(function(data) {
                            if (data == 1) {
                                $("#modal-member").modal('hide');
                                setTimeout(function()
                                {
                                    $("#load_member").load("MemberMainPage.php?search_condition=search_all", function() {
                                        $.unblockUI();
                                    });
                                    $.gritter.add({
                                        title: 'Success!',
                                        text: "<?= $config['msg_edit_success'] ?>"
                                    });
                                }
                                , 500);

                            } else {
                                alert(data);
                            }
                        });
                    } else {
                        var jqxhr = $.post("model/EditMember.php?memId=" + memId + "&memName=" + memName + "&memRole=" + memRole + "&memberSkill=" + memberSkill + "&teamCode=" + teamCode + "&teamName=" + teamName + "&tel=" + tel + "&email=" + email + "&remark=" + remark_inform);
                        jqxhr.success(function(data) {
                            if (data == 1) {
                                $("#modal-member").modal('hide');
                                setTimeout(function()
                                {
                                    $("#load_member").load("MemberMainPage.php?searchCondition=search_all", function() {
                                        $.unblockUI();
                                    });
                                    $.gritter.add({
                                        title: 'Success!',
                                        text: "<?= $config['msg_edit_success'] ?>"
                                    });
                                }
                                , 500);

                            } else {
                                alert(data);
                            }
                        });
                    }

                }
            } else {
                var jqxhr = $.post("model/SavingMember.php?memId=" + memId + "&memName=" + memName + "&memRole=" + memRole + "&memberSkill=" + memberSkill + "&teamCode=" + teamCode + "&teamName=" + teamName + "&tel=" + tel + "&email=" + email + "&remark=" + remark_inform);
                jqxhr.success(function(data) {
                    if (data == 1) {
                        $("#modal-member").modal('hide');
                        setTimeout(function()
                        {
                            $("#load_member").load("MemberMainPage.php?searchCondition=search_all", function() {
                                $.unblockUI();
                            });
                            $.gritter.add({
                                title: 'Success!',
                                text: "<?= $config['msg_save_success'] ?>"
                            });
                        }
                        , 500);

                    } else {
                        alert(data);
                    }
                });
            }
        });
    });
    function deleteMember(memID) {
        if (confirm("Are you sure?"))
        {
            blockPage();
            var jqxhr = $.post("model/DeleteMember.php?mem_id=" + memID);
            jqxhr.success(function(data) {
                if (data == 1) {
                    setTimeout(function()
                    {
                        $("#load_member").load("MemberMainPage.php?searchCondition=search_all", function() {
                            $.unblockUI();
                        });

                        $.gritter.add({
                            title: 'Success!',
                            text: "<?= $config['msg_delete_success'] ?>"
                        });
                    }
                    , 500);
                } else {
                    alert("ไม่สามารถลบข้อมูลได้");
                }
            });
            jqxhr.error(function(data) {
                window.location.replace("error.php?error_msg=" + data);
            });
        }
        else
        {
            e.preventDefault();
        }

    }
    function editMember(memID) {
        blockPage();
        createOrEditState = "Edit";
        var jqxhr = $.post("model/GetAllMemberForEdit.php?mem_id=" + memID);
        jqxhr.success(function(data) {
            $.unblockUI();
            $("#waringmsg").append("Leave empty for no change");
            obj = JSON.parse(data);
            $("#member_id_form").val(obj.mem_id);
            $("#member_name_form").val(obj.mem_name);
            $("#member_role_form").val(obj.mem_role);
            $("#hideMemSkill").val(obj.mem_skill);
            $("#team_code_in_member_form2").val(obj.mem_t_code);
            $("#team_name_in_member_form2").val(obj.mem_t_name);
            $("#tel_in_member_form").val(obj.mem_tel);
            $("#email_in_member_form").val(obj.mem_email);
            $("#remark_inform").val(obj.mem_remark);

        });
        jqxhr.error(function(data) {
            window.location.replace("error.php?error_msg=" + data);
        });
    }
    function blockPage() {
        $.blockUI({message: 'Operation in progress...', css: {
                border: 'none',
                padding: '15px',
                backgroundColor: '#000',
                '-webkit-border-radius': '10px',
                '-moz-border-radius': '10px',
                opacity: .5,
                color: '#fff'
            }});
    }
</script>